package edu.task.service.impl;

import edu.task.mapper.Mapper;
import edu.task.model.*;
import edu.task.model.vo.SysTaskVO;
import edu.task.repository.*;
import edu.task.service.SysTaskService;
import edu.task.utils.BeanUtils;
import edu.task.utils.StringUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SysTaskServiceImpl implements SysTaskService {

    @Autowired
    SysTaskRepository sysTaskRepository;

    @Autowired
    Mapper mapper;

    @Autowired
    SysProjectTaskRepository sysProjectTaskRepository;

    @Autowired
    SysUserTaskRepository sysUserTaskRepository;

    @Autowired
    SysTaskSubtaskRepository sysTaskSubtaskRepository;

    @Autowired
    SysSubtaskRepository sysSubtaskRepository;

    @Autowired
    SysUserMsgRepository sysUserMsgRepository;

    @Autowired
    SysMsgRepository sysMsgRepository;

    @Autowired
    SysUserRepository sysUserRepository;

    @Autowired
    private JavaMailSender mailSender;


    @Override
    public List<SysTask> selectTaskList() {
        return sysTaskRepository.findAll();
    }

    /**
     * 新增任务
     * @param task
     * @return
     */
    @Override
    @Transactional
    public boolean insertTask(SysTaskVO task) {
        SysTask sysTask = new SysTask();
        BeanUtils.copyProperties(task, sysTask);

        // 添加创建时间信息
        Date day = new Date();
        sysTask.setCreateTime(day);
        sysTask.setUpdateTime(day);
        sysTask.setStatus("0");

        sysTask.setWorkingHours(sysTask.getWorkingHours()+":00:00");
        sysTask.setSurplus(sysTask.getWorkingHours());

        Date date = new Date();
        String[] sum = sysTask.getWorkingHours().split(":");
        int[] array = Arrays.asList(sum).stream().mapToInt(Integer::parseInt).toArray();
        long time = sysTask.getCreateTime().getTime();
        for (int i=0;i<array.length;i++){
            if (i==0){
                time = time + array[i]*1000*60*60;
            } else if (i==1) {
                time = time + array[i]*1000*60;
            } else if (i==2) {
                time = time + array[i]*1000;
            }
        }
        date.setTime(time);
        sysTask.setEstimatedTime(date);


        for (Long userId : task.getUserIds()) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser = sysUserRepository.findOne(Example.of(sysUser)).get();
            sysTask.setConscientious(sysUser.getUserName());
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(task.getCreateUserId());
        sysUser = sysUserRepository.findOne(Example.of(sysUser)).get();
        sysTask.setCreateBy(sysUser.getCreateBy());
        sysTask.setUpdateBy(sysUser.getUpdateBy());

//        mapper.insertTask(sysTask);
        sysTaskRepository.save(sysTask);
        task.setTaskId(sysTask.getTaskId());
        //新增项目与任务关联
        insertProjectTask(task);

        if (StringUtils.isNotNull(task.getUserIds()) || task.getUserIds().length != 0) {
            insertUserTask(task, true);
        }
        return null != sysTask.getTaskId();
    }

    @Transactional
    public int insertProjectTask(SysTaskVO task) {
        Long[] projects = task.getProjectIds();
        if (StringUtils.isNull(projects) || projects.length == 0) {
            return 0;
        }
        Long[] taskIds = new Long[projects.length];
        Long taskId = task.getTaskId();
        for (Long projectId : projects) {
            SysProjectTask sysProjectTask = new SysProjectTask();
            sysProjectTask.setProjectId(projectId);
            sysProjectTask.setTaskId(taskId);
            sysProjectTaskRepository.save(sysProjectTask);
        }
        Arrays.fill(taskIds, task.getTaskId());
        return 1;
    }

    @Transactional
    public int insertUserTask(SysTaskVO task, boolean find) {
        Long[] users = task.getUserIds();
        if (StringUtils.isNull(users) || users.length == 0) {
            return 0;
        }
        Long[] taskIds = new Long[users.length];
        Long taskId = task.getTaskId();
        for (Long userId : users) {
            SysUserTask sysUserTask = new SysUserTask();
            sysUserTask.setUserId(userId);
            sysUserTask.setTaskId(taskId);
            sysUserTaskRepository.save(sysUserTask);

            // 用户消息提醒
            if (find) {
                SysMsg sysMsg = new SysMsg();

                sysMsg.setContent("您有一个名为" + task.getTaskName() + "的新任务！");
                mapper.insertMsg(sysMsg);
                Long msgId = sysMsg.getMsgId();
                SysUserMsg sysUserMsg = new SysUserMsg();
                sysUserMsg.setUserId(userId);
                sysUserMsg.setMsgId(msgId);
                sysUserMsgRepository.save(sysUserMsg);

                // 发邮件消息
                sendMailTest(userId, task.getTaskName());
            }

        }
        Arrays.fill(taskIds, task.getTaskId());
        return 1;
    }

    @SneakyThrows
    private void sendMailTest(Long userId, String content ) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setDelFlag("0");
        SysUser sysUser1 = sysUserRepository.findOne(Example.of(sysUser)).get();

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        String nick = MimeUtility.encodeText("任务系统");
        simpleMailMessage.setFrom(String.valueOf(new InternetAddress(nick+ "<"+ "2930742015@qq.com"+ ">")));
        simpleMailMessage.setTo(sysUser1.getEmail());
        simpleMailMessage.setSubject("任务消息");
        simpleMailMessage.setText("您有一个名为" + content + "的新任务待查看！");

        mailSender.send(simpleMailMessage);
    }

    @Override
    @Transactional
    public int deleteTaskById(Long taskId) {
        sysProjectTaskRepository.deleteProjectTaskByTaskId(taskId);
        sysUserTaskRepository.deleteUserTaskByTaskId(taskId);

        // 删除任务关联子任务
        List<Long> subtasks = sysTaskSubtaskRepository.selectSubtaskIdByTaskId(taskId);
        for (int i = 0 ; i < subtasks.size();i++){
            sysSubtaskRepository.deleteSubtaskById(subtasks.get(i));
        }
        sysTaskSubtaskRepository.deleteTaskSubtaskByTaskId(taskId);

        return sysTaskRepository.deleteTaskById(taskId);
    }

    @SneakyThrows
    @Override
    @Transactional
    public boolean updateTask(SysTaskVO task) {
        Long taskId = task.getTaskId();
        Optional<SysTask> op = sysTaskRepository.findById(taskId);
        //判断optional是否为空
        if (!op.isPresent()) {
            return false;
        }

        SysTask sysTask = op.get();
        BeanUtils.copyPropertiesIgnoreNull(task, sysTask);

        if (sysTask.getStatus().equals("1")){
            Date date =new Date();
            String time = String.valueOf(date);
            sysTask.setEndTime(time);
        }

        //更新任务信息
        sysTaskRepository.save(sysTask);

        return null != sysTask.getTaskId();
    }

    @Override
    public List<SysTask> selectTaskById(List<Long> taskId) {
        List<SysTask> tasks = new ArrayList<>();
        for (int i=0 ;i<taskId.size();i++) {
            SysTask sysTask =new SysTask();
            sysTask.setTaskId(taskId.get(i));
            tasks.add(sysTaskRepository.findOne(Example.of(sysTask)).get());
        }
        return tasks;
    }

    @Override
    public List<Long> selectTaskListByProjectId(Long projectId) {
        return sysTaskRepository.selectTaskListByProjectId(projectId);
    }

    @Override
    public List<Long> selectTaskListByUserId(Long userId) {
        return sysTaskRepository.selectTaskListByUserId(userId);
    }

    @Override
    public List<SysTask> selectTaskByTaskId(List<Long> taskIds) {
        List<SysTask> tasks = new ArrayList<>();
        SysTask sysTask = new SysTask();
        for (int i=0 ; i<taskIds.size();i++) {
            sysTask.setTaskId(taskIds.get(i));
            tasks.add(sysTaskRepository.findOne(Example.of(sysTask)).get());
        }
        return tasks;
    }

    @Override
    public List<SysTask> selectTaskListByStatus() {
        return sysTaskRepository.selectTaskListByStatus();
    }

    @Override
    public SysTask updateTasks(SysTask task) {
        return sysTaskRepository.save(task);
    }

    /**
     * 将时间戳后转时分秒格式
     * @param time
     * @return
     */
    @Override
    public String getTimeString(long time) {
        if (time > 0) {
            long second = time / 1000;
            long seconds = second % 60;
            long minutes = second / 60;
            long hours = minutes / 60;
            minutes = minutes % 60;
            String timeString = "";
            if (seconds < 10) {
                timeString = ":0" + seconds;
            } else {
                timeString = ":" + seconds;
            }
            if (minutes < 10) {
                timeString = ":0" + minutes + timeString;
            } else {
                timeString = ":" + minutes + timeString;
            }
            if (hours < 10) {
                timeString = "0" + hours + timeString;
            } else {
                timeString = hours + timeString;
            }
            return timeString;
        } else {
            return "00:00:00";
        }
    }

}
